//
//  DailyDetailsViewController.m
//  MagicZhao
//
//  Created by hy002 on 2017/12/18.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "DailyDetailsViewController.h"
#import "dailyImgModel.h"

static NSString *cellPath = @"dailydetailCell";
@interface DailyDetailsViewController ()<UITableViewDelegate,UITableViewDataSource, UITextViewDelegate>
{
    UITextView *postilTextView;
}
@property (nonatomic, strong)UITableView *tableview;
@property (strong, nonatomic) UILabel *plaLabel;
@property (strong, nonatomic) NSString *textViewStr;
@property (nonatomic, assign) CGFloat tableViewOffsetY;
@end

@implementation DailyDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _textViewStr = _projectModel.remark;
    [self creatUI];
    //注册通知,监听键盘出现
//    [[NSNotificationCenter defaultCenter]addObserver:self
//                                            selector:@selector(handleKeyboardDidShow:)
//                                                name:UIKeyboardDidShowNotification
//                                              object:nil];
//    //注册通知，监听键盘消失事件
//    [[NSNotificationCenter defaultCenter]addObserver:self
//                                            selector:@selector(handleKeyboardDidHidden)
//                                                name:UIKeyboardDidHideNotification
//                                              object:nil];
}

//- (void)dealloc {
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
//}

- (void)creatUI
{
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(onClickEnsureBtn)];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"项目日报";
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tableview];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    singleTap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:singleTap];
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap {
    [self.view endEditing:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 2;
    }
    else if (section == 1)
    {
        NSArray *imgAry = _projectModel.dailyImgs;
        return imgAry.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            UILabel *projectNameLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, SCREEN_WIDTH-30*displaywidth, 40*displaywidth) Font:16.0 Text:_projectModel.projectname Color:RGB(51, 51, 51)];
            [cell.contentView addSubview:projectNameLab];
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 49*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
            lineView.backgroundColor = LinesColor;
            [cell.contentView addSubview:lineView];
            
        }
        else if (indexPath.row == 1)
        {
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"toux"];
            [imgView sd_setImageWithURL:[NSURL URLWithString:_projectModel.user.headImg] placeholderImage:[UIImage imageNamed:@"toux"]];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.layer.masksToBounds = YES;
            [cell.contentView addSubview:imgView];
            UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(60*displaywidth, 15*displaywidth, 150*displaywidth, 25*displaywidth) Font:13.0 Text:_projectModel.user.name Color:RGB(77, 77, 77)];
            [cell.contentView addSubview:nameLab];
            NSString *timeStr = _projectModel.createDtm;
            if (timeStr.length > 15)
            {
                timeStr = [timeStr substringToIndex:_projectModel.createDtm.length-3];
            }
            UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH-180*displaywidth, 15*displaywidth, 165*displaywidth, 25*displaywidth) Font:12.0 Text:timeStr Color:RGB(153, 153, 153)];
            timeLab.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:timeLab];
            UILabel *contenLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 60*displaywidth, SCREEN_WIDTH-30*displaywidth, 25*displaywidth) Font:13.0 Text:_projectModel.content Color:RGB(77, 77, 77)];
            CGRect bounds = [contenLab.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-30*displaywidth, 5000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(13.0+fontScale) forKey:NSFontAttributeName] context:nil];
            contenLab.frame = CGRectMake(15*displaywidth, 60*displaywidth, SCREEN_WIDTH-30*displaywidth, bounds.size.height+20*displaywidth);
            [cell.contentView addSubview:contenLab];
        }
    }
    else if(indexPath.section == 1)
    {
        [self confirmCell:cell atIndexPath:indexPath];
        
        
    }
    else
    {
        UILabel *titleLab =  [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, SCREEN_WIDTH-30*displaywidth, 30*displaywidth) Font:16.0 Text:@"批注" Color:RGB(51, 51, 51)];
        [cell.contentView addSubview:titleLab];
//            UILabel *remarkLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 35*displaywidth, SCREEN_WIDTH-30*displaywidth, 25*displaywidth) Font:13.0 Text:_projectModel.remark Color:RGB(77, 77, 77)];
//            CGRect bounds = [remarkLab.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-30*displaywidth, 5000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(13.0+fontScale) forKey:NSFontAttributeName] context:nil];
//            remarkLab.frame = CGRectMake(15*displaywidth, 35*displaywidth, SCREEN_WIDTH-30*displaywidth, bounds.size.height+20*displaywidth);
//            [cell.contentView addSubview:remarkLab];
        postilTextView = [[UITextView alloc] init];
        postilTextView.frame = CGRectMake(15*displaywidth, 35*displaywidth, SCREEN_WIDTH-30*displaywidth, 190*displaywidth);
        postilTextView.font = [UIFont systemFontOfSize:14];
        postilTextView.delegate = self;
        postilTextView.text = _textViewStr;
        postilTextView.textColor = UIColorHexValue(0x4D4D4D);
        postilTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        postilTextView.layer.borderWidth = 0.5;
        [cell.contentView addSubview:postilTextView];
        _plaLabel = [ZCControl createLabelWithFrame:CGRectMake(5, 5, 170, 21) Font:14 Text:@"请输入批注内容" Color:UIColorHexValue(0x999999)];
        if (_textViewStr.length > 0) {
            _plaLabel.hidden = YES;
        }
        [postilTextView addSubview:_plaLabel];
        
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            return 50*displaywidth;
        }
        else
        {
            CGRect bounds = [_projectModel.content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-30*displaywidth, 5000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(13.0+fontScale) forKey:NSFontAttributeName] context:nil];
            return bounds.size.height+80*displaywidth;
        }
        
    }
    else if (indexPath.section == 1)
    {
        
        NSArray *imgAry = _projectModel.dailyImgs;
        if (imgAry.count == 0)
        {
            return 0;
        }
        dailyImgModel *imgModel = imgAry[indexPath.row];
        UIImage *img = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgModel.url];
        if (!img) {
            return 150*displaywidth;
        }
        CGFloat height = img.size.height;
        return (height/img.size.width)*(SCREEN_WIDTH-30*displaywidth)+10*displaywidth;
    }
    else
    {
        return 240;
    }
}

- (void)confirmCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSArray *imgAry = _projectModel.dailyImgs;
    dailyImgModel *imgModel = imgAry[indexPath.row];
    UIImageView *bigImgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, SCREEN_WIDTH-30*displaywidth, 150*displaywidth) ImageName:@""];
    bigImgView.contentMode = UIViewContentModeScaleAspectFill;
    bigImgView.layer.masksToBounds = YES;
    [cell.contentView addSubview:bigImgView];
    UIImage *cachedImg = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgModel.url];
    if (!cachedImg) {
        [self downloadImage:imgModel.url forIndexPath:indexPath];
    }else{
        bigImgView.image  = cachedImg;
         CGFloat height = cachedImg.size.height;
        bigImgView.frame = CGRectMake(15*displaywidth, 5*displaywidth, SCREEN_WIDTH-30*displaywidth, (height/cachedImg.size.width)*(SCREEN_WIDTH-30*displaywidth));
    }
}

- (void)downloadImage:(NSString *)imageURL forIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self) weakSelf = self;
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageURL]
                                                          options:2
                                                         progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                                         }
                                                        completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                                            [[SDImageCache sharedImageCache] storeImage:image forKey:imageURL toDisk:YES];
                                                            [weakSelf performSelectorOnMainThread:@selector(reloadCellAtIndexPath:) withObject:indexPath waitUntilDone:NO];
                                                            
                                                        }];
}
- (void)reloadCellAtIndexPath:(NSIndexPath *)indexPath
{
    [_tableview reloadData];
}

// MARK: UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 0) {
        self.plaLabel.hidden = YES;
    } else {
        self.plaLabel.hidden = NO;
    }
    _textViewStr = textView.text;
}

//限制textView输入字数
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    //这个判断相当于是textfield中的点击return的代理方法
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    //在输入过程中 判断加上输入的字符 是否超过限定字数
//    NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text];
//    if (str.length > 256)
//    {
//        self.plaLabel.hidden = YES;
//        textView.text = [str substringToIndex:256];
//        [self.countLabel setText:@"256/256"];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"输入的内容超过限制" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        return NO;
//    }else{
//        NSLog(@"%lu",(unsigned long)textView.text.length);
//    }
    return YES;
}

- (void)onClickEnsureBtn {
    if ([postilTextView.text isEqual:@""]) {
        [LTools showMBProgressWithText:@"请输入批注内容" addToView:self.view];
        return;
    }
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestDailySaveParmers:@{@"id" : _projectModel.ID, @"remark" : postilTextView.text} Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             [LTools showMBProgressWithText:@"保存成功" addToView:weakSelf.view];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

//监听事件
//- (void)handleKeyboardDidShow:(NSNotification*)paramNotification
//{
//    //获取键盘高度
//    NSValue *keyboardRectAsObject=[[paramNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
//
//    CGRect keyboardRect;
//    [keyboardRectAsObject getValue:&keyboardRect];
//    [UIView animateWithDuration:0.275 animations:^{
//        self.tableview.frame = CGRectMake(0, -keyboardRect.size.height, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX);
//    }];
//}
//
//- (void)handleKeyboardDidHidden
//{
//    [UIView animateWithDuration:0.275 animations:^{
//        self.tableview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX);
//    }];
//}

- (void)textViewDidEndEditing:(UITextView *)textView {
    _textViewStr = textView.text;
}

// 我们为了防止tableView不能返回原始没有被点击的位置(这是防止用户在键盘弹出的时候，在滑动而造成的混乱)
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    /* 防止错乱停止编辑*/
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
